<script type="text/javascript">

    // 按钮模版
    const menu_item_template = `
<div class="menu-item">

  <div id="menu-top-{menu_index}" data-index="{menu_index}" class="menu-item-sub">

  </div>

  <div class="layui-btn-group">
    <button id="menu-{menu_index}" data-index="{menu_index}" type="button" menu-top class="layui-btn layui-btn-primary layui-btn-sm">{menu_name}</button>
    <button data-index="{menu_index}" menu-sub-add type="button" class="layui-btn layui-btn-primary layui-btn-sm">
        <i class="layui-icon layui-icon-add-1"></i>
    </button>
  </div>
</div>
      `

    const menu_sub_template = `
<div class="ptb5">
    <button id="menu-sub-{menu_index}" data-sub-index="{menu_index}" type="button"  menu-sub class="layui-btn layui-btn-primary layui-btn-sm">{menu_name}</button>
</div>`

    /**
     * 菜单初始化
     * @param menus
     */
    const wechatMenuInit = function (menus) {
        let menu_list = ''
        for (let i in menus) {
            let data = menus[i]
            let template = menu_item_template.replace('{menu_name}', data.name)
            template = template.replaceAll('{menu_index}', i)
            menu_list += template
        }

        $('#menu-list').html(menu_list)

        menuSubInit(menus)
    }

    const menuSetting = function (form, data) {

        menuTypeChoose(data.type)

        let value = {
            'menu_name': data.name,
            'menu_type': data.type,
        }

        if (data.type === 'media_id') {
            value['menu_media_id'] = data.media_id
        }

        if (data.type === 'miniprogram') {
            value['menu_appid'] = data.appid
            value['menu_pagepath'] = data.pagepath
        }

        if (data.url) {
            value['menu_url'] = data.url
        }

        if (data.type === 'click') {
            value['menu_key'] = data.key
        } else {
            value['menu_key'] = ''
        }

        form.val('menu-setting', value)
    }

    const menuTypeChoose = function (type) {

        $('#menu-type-click').addClass('layui-hide')
        $('#menu-type-miniprogram').addClass('layui-hide')
        $('#menu-type-media-id').addClass('layui-hide')
        $('#menu-type-article-id').addClass('layui-hide')
        $('#menu-type-url').addClass('layui-hide')

        if (type === 'miniprogram') {
            $('#menu-type-miniprogram').removeClass('layui-hide')
            $('#menu-type-url').removeClass('layui-hide')
        } else if (type === 'media_id' || type === 'view_limited') {
            $('#menu-type-media-id').removeClass('layui-hide')
        } else if (type === 'article_id' || type === 'article_view_limited') {
            $('#menu-type-article-id').removeClass('layui-hide')
        } else if (type === 'view') {
            $('#menu-type-url').removeClass('layui-hide')
        } else {
            $('#menu-type-click').removeClass('layui-hide')
        }
    }

    /**
     * 子按钮渲染
     */
    const menuSubInit = function (menus) {

        for (let i in menus) {
            let data = menus[i] || null
            let sub_button = data.sub_button || null
            if (sub_button) {
                let template = ''
                for (let j in sub_button) {
                    let tmp = sub_button[j]
                    let t = menu_sub_template.replace('{menu_name}', tmp.name)
                    t = t.replaceAll('{menu_index}', j)
                    template += t
                }

                let obj = $('#menu-top-' + i)
                if (obj.length) {
                    obj.html(template)
                    obj.show()
                }
            }
        }
    }

    const getCurrentMenu = function () {

        // 获取选中的一级菜单
        let menu_top = $('#menu-list .menu-item [menu-top].layui-btn-normal')
        // 一级菜单的索引
        let index = -1
        if (menu_top.length) {
            index = menu_top.data('index')
        }

        // 获取选中的二级菜单
        let menu_sub = $('#menu-list .menu-item [menu-sub].layui-btn-normal')
        // 子菜单的索引
        let sub_index = -1
        if (menu_sub.length) {
            sub_index = menu_sub.data('sub-index')
        }

        return {
            top: {
                obj: menu_top,
                index: index,
            },
            sub: {
                obj: menu_sub,
                index: sub_index,
            }
        }

    }

    const saveMenu = function (form) {

        let current = getCurrentMenu()

        if (current.sub.index >= 0) {

            // 一级菜单的索引
            let index = current.top.index

            // 子菜单的索引
            let sub_index = current.sub.index

            // 表单数据
            let data = form.val('menu-setting')

            current.sub.obj.text(data.menu_name)
            menus[index]['sub_button'][sub_index]['name'] = data.menu_name
            menus[index]['sub_button'][sub_index]['type'] = data.menu_type

            if (data.menu_type === 'view' || data.menu_type === 'miniprogram') {
                menus[index]['sub_button'][sub_index]['url'] = data.menu_url
            }

            if (data.menu_type === 'miniprogram') {
                menus[index]['sub_button'][sub_index]['appid'] = data.menu_appid
                menus[index]['sub_button'][sub_index]['pagepath'] = data.menu_pagepath
            }

            if (data.menu_type === 'media_id') {
                menus[index]['sub_button'][sub_index]['media_id'] = data.menu_media_id
            }

            return false
        }

        if (current.top.index >= 0) {
            // 表单数据
            let data = form.val('menu-setting')
            current.top.obj.text(data.menu_name)
            menus[index]['name'] = data.menu_name
        }
    }

    const menuInit = function (layui) {

        let form = layui.form
        let toast = layui.toast

        // 菜单初始化
        wechatMenuInit(menus)

        // 添加子菜单
        $('#menu-add').on('click', function () {
            let menu_list = $('#menu-list')
            let len = menu_list.find('.menu-item').length
            if (len < 3) {
                let name = '菜单名称' + len
                let temp = menu_item_template.replace('{menu_name}', name)
                temp = temp.replaceAll('{menu_index}', len)
                menu_list.append(temp)
                menus[len] = {
                    name: name,
                    type: 'click',
                    key: 'key' + len
                }
            }
        })

        // 删除子菜单
        $('#menu-setting-remove').on('click', function () {
            // 获取选中的二级菜单
            let current = getCurrentMenu()

            if (current.sub.index >= 0) {
                let index = toast.confirm(lang.confirm_delete || '请再次确认是否删除子菜单?', function () {
                    menus[current.top.index]['sub_button'].splice(current.sub.index, 1)
                    layer.close(index)
                    menuSubInit(menus)
                })
                return false
            }

            if (current.top.index >= 0) {
                let index = toast.confirm(lang.confirm_delete || '请再次确认是否删除菜单?', function () {
                    menus.splice(current.top.index, 1)
                    current.top.obj.parents('.menu-item').remove()
                    layer.close(index)
                    menuSubInit(menus)
                })
                return false
            }
        })

        // 一级菜单点击事件
        $('#menu-list').on('click', '.menu-item [menu-top]', function () {

            $('#menu-list .menu-item [menu-top]').removeClass('layui-btn-normal').addClass('layui-btn-primary')

            $(this).removeClass('layui-btn-primary').addClass('layui-btn-normal')

            $('[menu-sub]').removeClass('layui-btn-normal').addClass('layui-btn-primary')

            let index = $(this).data('index')
            let data = menus[index] || null
            if (!data) {
                data = {
                    name: $(this).text(),
                    type: 'click'
                }
            }

            menuSetting(form, data)
        })

        // 添加子菜单
        $('#menu-list').on('click', '[menu-sub-add]', function () {

            let index = $(this).data('index')

            let sub_button = []
            try {
                sub_button = menus[index]['sub_button'] || []
            } catch (e) {
                sub_button = []
            }

            if (sub_button.length >= 5) {
                return false
            }

            sub_button.push({
                'name': '子菜单名称',
                'key': 'key',
                'type': 'click'
            })

            menus[index]['sub_button'] = sub_button

            menuSubInit(menus)
        })

        // 子菜单点击事件
        $('#menu-list').on('click', '[data-sub-index]', function () {

            $('#menu-list .menu-item [data-sub-index]').removeClass('layui-btn-normal').addClass('layui-btn-primary')
            $(this).removeClass('layui-btn-primary').addClass('layui-btn-normal')

            let parent = $(this).parents('[data-index]')

            // 选中父级菜单
            $('[menu-top]').removeClass('layui-btn-normal').addClass('layui-btn-primary')
            parent.next('.layui-btn-group').find('[menu-top]').removeClass('layui-btn-primary').addClass('layui-btn-normal')

            let index = parent.data('index')
            let sub_button = menus[index]['sub_button'] || null

            if (!sub_button) {
                return false
            }

            index = $(this).data('sub-index')

            let data = sub_button[index]

            menuSetting(form, data)
        })
    }
</script>